from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from .models import User
from . import constants

def check_verify_email_token(token):
    '''反序列化token找到user'''
    '''通过序列化信息先找到序列化对象token'''
    serializer = Serializer(settings.SECRET_KEY,constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        '''通过loads反序列化字典'''
        data = serializer.loads(token)
    except BadData:
        '''如果有错则返回None'''
        return None
    else:
        '''从data中取出userid和email'''
        user_id = data.get('user_id')
        email = data.get('email')
        '''然后通过userid和email查询到user，因为是get方法出错会报错，所以需要try'''
        try:
            user = User.objects.get(id = user_id,email=email)
            '''如果查不到则返回None，查到了就返回信息'''
        except User.DoesNotExist:
            return None
        else:
            return user
def generate_verify_email_url(user):
    '''生成验证邮箱链接'''
    '''报错导不了又造不了的就设置成参数'''
    serializer = Serializer(settings.SECRET_KEY,constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id':user.id,'email':user.email}
    token = serializer.dumps(data).decode()
    return settings.EMAIL_VERIFY_URL +'?token='+ token


def get_user_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try :
        if re.match(r'^1[3-9]\d{9}$',account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    # 自定义用户认证客户端
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号
        user = get_user_by_account(username)
        # 校验user是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user